﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace COFE.Core.Actions
{
    public class IntervalSchedule : ScheduleBase
    {
        public IntervalSchedule(WorkPriority priority, TimeSpan interval, IWork work)
            : base(priority, work)
        {
            if (priority == WorkPriority.NotReady)
                throw new ArgumentException();            
            _interval = interval;
        }

        #region Methods

        /// <summary>
        /// Will set IsFinished, and the work will be removed 
        /// from the scheduler queue in its next run.
        /// </summary>
        public void Abort()
        {
            _aborted = true;
        }

        #endregion

        #region Data
        
        bool _aborted = false;
        TimeSpan _interval;

        #endregion

        #region Public Properties

        public override bool CheckCanRetry()
        {
            if (Work.WorkStatus == StatusType.Error)
                return !_aborted && base.CheckCanRetry();
            return !_aborted;
        }        

        public override WorkPriority Priority
        {
            get
            {
                switch (Work.WorkStatus)
                {
                    case StatusType.Working :
                    case StatusType.Paused : 
                        //If the work is already running, then end time is not valid.
                        return WorkPriority.NotReady;
                    default :
                        //If time elpased, default priority, otherwise notready.
                        return Work.EndTimeUtc.Add(_interval) <
                            DateTime.UtcNow ? base.Priority 
                            : WorkPriority.NotReady;
                }                
            }
            protected set { base.Priority = value; }            
        }
        public override bool IsFinished { get { return _aborted; } }
        
        #endregion

    }
}
